package com.faiz.algorithm;

public class SearchWord {
    //结果
    private boolean res = false;
    //x长度
    private int x;
    //y长度
    private int y;
    //多要查询的单词长度
    private int l;

    public boolean exist(char[][] board, String word) {
        //这个就是回溯算法最好的应用了
        this.x = board.length - 1;
        this.y = board[0].length - 1;
        this.l = word.length() - 1;

        boolean[][] visited = new boolean[x + 1][y + 1];
        for (int i = 0; i <= x; i++) {
            for (int j = 0; j <= y; j++) {
                if (board[i][j] == word.charAt(0)) {
                    backTrace(board, visited, word, 0, i, j);
                }
                if (res) {
                    break;
                }
            }
            if (res) {
                break;
            }
        }
        return res;
    }

    /**
     * @param board   查询的数组
     * @param visited 是否已经被访问
     * @param word    查询的目标单词
     * @param index   当前查询/已经匹配的单词
     */
    public void backTrace(char[][] board, boolean[][] visited, String word, int index, int m, int n) {
        //如果已经被访问过了，就直接return
        if (visited[m][n]) {
            return;
        }
        //如果已经匹配完成就直接返回true
        if (index > l) {
            res = true;
            return;
        }
        //这里我们按照右下左上的方位来进行处理
        if (board[m][n] == word.charAt(index)) {
            visited[m][n] = true;
            if (index >= l) {
                res = true;
                return;
            }
            if (n < y) {
                backTrace(board, visited, word, index + 1, m, n + 1);
            }
            if (m < x) {
                backTrace(board, visited, word, index + 1, m + 1, n);
            }
            if (n > 0) {
                backTrace(board, visited, word, index + 1, m, n - 1);
            }
            if (m > 0) {
                backTrace(board, visited, word, index + 1, m - 1, n);
            }
            visited[m][n] = false;
        }
    }
}
